package com.dilidili.service.impl;

import com.dilidili.entity.User;
import com.dilidili.mapper.LoginMapper;
import com.util.AesUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @PackgeName: com.jab.service.impl
 * @ClassName: UsersDetailServiceImpl
 * @Author: 零
 * Date: 2022/3/22 15:51
 * project name: SpringCloud-Exercise
 * @Version:
 * @Description:
 */
@Component
public class UsersDetailServiceImpl implements UserDetailsService {

    @Autowired
    private LoginMapper loginMapper;


    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        System.out.println(s);
        User login = loginMapper.login(s);
        if (s.equals(login.getUsername())) {
            String secretKey="1111111111111111";
            String decrypt = AesUtil.decrypt(login.getUserPassword(),secretKey );
            login.setUserPassword(new BCryptPasswordEncoder().encode(decrypt));
            List<GrantedAuthority> list = new ArrayList<GrantedAuthority>();
            SimpleGrantedAuthority authority = new SimpleGrantedAuthority("user");
            list.add(authority);
            login.setAuthorities(list);
        } else {
            throw new UsernameNotFoundException("账号不存在");
        }
        return login;
    }

    public static void main(String[] args) {
        String pwd = "admin";
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        System.out.println(passwordEncoder.encode(pwd));
    }
}
